//
//  APDiscoveryViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/1.
//

#import "APDiscoveryViewController.h"
#import "APDiscoveryContetListLayout.h"
#import "APDiscoveryCollectionViewCell.h"
#import "APDiscoveryDataManager.h"
#import "APWorksModel.h"
#import "SDWebImage.h"
#import "APBottomMenuViewController.h"
#import "APWorksDetailViewController.h"
#import "APUserPageViewController.h"
#import "APPublishWorksViewController.h"
#import "APLoginManager.h"
#import "APHomeDataManager.h"
#import "APUnlockAlertViewController.h"

@interface APDiscoveryViewController ()<UICollectionViewDataSource,APDiscoveryContetListLayoutDelegate,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *cameraButton;
@end

@implementation APDiscoveryViewController

- (UIButton *)cameraButton{
    if (!_cameraButton) {
        _cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cameraButton setBackgroundImage:[UIImage imageNamed:@"camera_icon"] forState:UIControlStateNormal];
        [_cameraButton addTarget:self action:@selector(cameraButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cameraButton;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [LYFont fontWithSize:24 fontName:LYFontNamepfr];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.text = @"Discovery";
    }
    return _titleLabel;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (UIImageView *)topImageView{
    if (!_topImageView) {
        _topImageView = [[UIImageView alloc] init];
        _topImageView.image = [UIImage imageNamed:@"table_header_icon"];
    }
    return _topImageView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        APDiscoveryContetListLayout *layout = [[APDiscoveryContetListLayout alloc] init];
        layout.interitemSpace = 10;
        layout.delegate = self;
        layout.lineSpace = 15;
        layout.columns = 2;
        layout.sectionInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.clearColor;
        [_collectionView registerClass:[APDiscoveryCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadBackground:@"discovery_list_bg"];
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(30);
        make.left.equalTo(self.view).offset(20);
    }];
    
    [self.view addSubview:self.cameraButton];
    [self.cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-19);
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(43, 29));
    }];
    [self.view addSubview:self.topImageView];
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(20);
        make.size.mas_equalTo(CGSizeMake(79, 70));
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topImageView).offset(47);
        make.left.right.bottom.equalTo(self.view);
    }];

}



- (void)cameraButtonDidClick:(UIButton *)sender{
    APPublishWorksViewController *publishVC = [[APPublishWorksViewController alloc] init];
    [publishVC setPublishCallBack:^(_Bool res, NSString * _Nullable msg) {
        if (res) {
            [self publishSuccessHander];
        }
    }];
    [self.navigationController pushViewController:publishVC animated:true];
}

- (void)publishSuccessHander{
    if ([[APHomeDataManager shareInstance] isBallUnlock:APBallTypeIntermediateWarrior]) {
        [self.view ShowProgressOnlyLabel:@"Post successfully"];
    }else{
        [[APHomeDataManager shareInstance] unlockBall:APBallTypeIntermediateWarrior];
        APUnlockAlertViewController *alertVC = [[APUnlockAlertViewController alloc] init];
        alertVC.ballType = APBallTypeIntermediateWarrior;
        [self.tabBarController presentViewController:alertVC animated:true completion:nil];
    }

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    APWorksModel *model = self.dataArray[indexPath.item];
    APWorksDetailViewController *worksVC = [[APWorksDetailViewController alloc] init];
    worksVC.worksModel = model;
    [self.navigationController pushViewController:worksVC animated:true];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = true;
    [self refreshData];
}


- (void)refreshData{
    WS(ws);
//    [self.view ShowProgress];
    [self.dataArray removeAllObjects];
    [[APDiscoveryDataManager shareInstance] loadData:^{
        for (APWorksModel *model in [APDiscoveryDataManager shareInstance].dataArray) {
           APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:model.userId];
            model.isFollow = userModel.isFriend;
//            LYLog(@"============%d",model.isBlock);
            if (!model.isBlock) {
                [ws.dataArray addObject:model];
            }
        }
        [ws.collectionView reloadData];
//        [ws.view removeProgress];
    }];
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGSize)worksListView:(UICollectionView *)listView layout:(APDiscoveryContetListLayout *)Layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (self.collectionView.bounds.size.width - 40) * 0.5;
    return CGSizeMake(width, 220);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    APDiscoveryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    APWorksModel *model = self.dataArray[indexPath.item];
    cell.upvoteButton.selected = model.upvote;
    cell.nameLabel.text = model.nickname;
    NSString *ballImage = [BaseDataManager ballImageName:model.ballType];
    [cell.ballButton setBackgroundImage:[UIImage imageNamed:ballImage] forState:UIControlStateNormal];
    cell.contentLabel.text = model.title;
    [cell.moreButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    BOOL isSelf = [[[APLoginManager shareInstance] userInfo].userId isEqualToString:model.userId];
    cell.moreButton.hidden = isSelf;
    if (model.isCreate) {
        UIImage *image =  [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",images_path,model.cover]];
        cell.coverImageView.image = image;
    }else{
        cell.coverImageView.image = [UIImage imageNamed:model.cover];
    }
    [cell.avatarControl.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
    [cell.upvoteButton addTarget:self action:@selector(upvoteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.avatarControl addTarget:self action:@selector(avatarButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.avatarControl.followButton.hidden = true;
    return cell;
}

- (void)avatarButtonDidClick:(APAvatarControl *)sender{

    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    APWorksModel *model = self.dataArray[indexPath.item];
    BOOL isSelf = [[[APLoginManager shareInstance] userInfo].userId isEqualToString:model.userId];
    if (isSelf) {
        return;
    }
    APUserPageViewController *userVC = [[APUserPageViewController alloc] init];
    userVC.userId = model.userId;
    [self.navigationController pushViewController:userVC animated:true];
}

- (void)upvoteButtonDidClick:(UIButton *)sender{
    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    APWorksModel *model = self.dataArray[indexPath.item];
    model.upvote = !model.upvote;
    [self.collectionView reloadData];
    [[APDiscoveryDataManager shareInstance] updateWorks:model.worksId];
}

- (void)moreButtonDidClick:(UIButton *)sender{
    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    APWorksModel *model = self.dataArray[indexPath.item];
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        [self refreshData];
    }];
    menuVC.userId = model.userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
    
}



- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    CGFloat top = self.view.safeAreaInsets.top > 0 ? self.view.safeAreaInsets.top:20;
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10 + top);
    }];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
  
    }
    return  self;
}


@end
